package thu.sorit.resolver;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;

public class Util {

	public static Bitmap getBitmapFromURL(String addr) {
	    try {
	        URL url = new URL(addr);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setRequestProperty("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11");
	        connection.connect();
	        InputStream input = connection.getInputStream();
	        Bitmap myBitmap = BitmapFactory.decodeStream(input);
	        return myBitmap;
	    } catch (IOException e) {
	        return null;
	    }
	}
	
	public static double getBitmapSimilarity(Bitmap pic1, Bitmap pic2) {
		final int r1[] = new int[256];
		final int g1[] = new int[256];
		final int b1[] = new int[256];
		final int r2[] = new int[256];
		final int g2[] = new int[256];
		final int b2[] = new int[256];
		Arrays.fill(r1, 0);
		Arrays.fill(g1, 0);
		Arrays.fill(b1, 0);
		Arrays.fill(r2, 0);
		Arrays.fill(g2, 0);
		Arrays.fill(b2, 0);
		for (int i = 0; i < pic1.getHeight(); ++i) {
			for (int j = 0; j < pic1.getWidth(); ++j) {
				int color = pic1.getPixel(j, i);
				++r1[Color.red(color)];
				++g1[Color.green(color)];
				++b1[Color.blue(color)];
			}
		}
		for (int i = 0; i < pic2.getHeight(); ++i) {
			for (int j = 0; j < pic2.getWidth(); ++j) {
				int color = pic2.getPixel(j, i);
				++r2[Color.red(color)];
				++g2[Color.green(color)];
				++b2[Color.blue(color)];
			}
		}
		return bhattacharyya(r1, r2) / 3 + bhattacharyya(g1, g2) / 3 + bhattacharyya(b1, b2) / 3;
	}
	
	public static int timeToDuration(String time) {
		String s[] = time.split(":");
		if (s.length == 3) {
			return Integer.parseInt(s[0]) * 3600 + Integer.parseInt(s[1]) * 60 + Integer.parseInt(s[2]);
		} else if (s.length == 2) {
			return Integer.parseInt(s[0]) * 60 + Integer.parseInt(s[1]); 
		} else {
			return -1;
		}
	}
	
	private static double bhattacharyya(int a[], int b[]) {
		assert(a.length == b.length);
		double sum = 0;
		int suma = 0;
		int sumb = 0;
		for (int i = 0; i < a.length; ++i) {
			sum += Math.sqrt(a[i] * b[i]);
			suma += a[i];
			sumb += b[i];
		}
		return sum / Math.sqrt(suma * sumb);
	}
	
}
